package juc;

/**
 * <pre>类名: ObjectWaitNotifyTest</pre>
 * <pre>描述: 等待-通知机制</pre>
 * <pre>版权: web_chen@163.com</pre>
 * <pre>日期: 2020/11/5 11:06</pre>
 * <pre>作者: chenwb</pre>
 */
public class ObjectWaitNotifyTest {

	/**
	 * 共享变量
	 */
	private int shareVal = 0;

	public synchronized void addShareVal1() throws InterruptedException {
		while (shareVal % 3 != 0) {
			wait();
		}
		shareVal++;
		System.out.println(shareVal);
		notifyAll();
	}

	public synchronized void addShareVal2() throws InterruptedException {
		while (shareVal % 3 != 1) {
			wait();
		}
		shareVal++;
		System.out.println(shareVal);
		notifyAll();
	}

	public synchronized void addShareVal3() throws InterruptedException {
		while (shareVal % 3 != 2) {
			wait();
		}
		shareVal++;
		System.out.println(shareVal);
		notifyAll();
	}

	public static void main(String[] args) throws InterruptedException {
		ObjectWaitNotifyTest objectWaitNotify = new ObjectWaitNotifyTest();
		Thread t1 = new Thread(() -> {
			try {
				for (; ; ) objectWaitNotify.addShareVal1();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		},"t1");

		Thread t2 = new Thread(() -> {
			try {
				for (;;) objectWaitNotify.addShareVal2();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		},"t2");

		Thread t3 = new Thread(() -> {
			try {
				for (; ; ) objectWaitNotify.addShareVal3();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		},"t3");

		t1.start();
		t2.start();
		t3.start();
		t1.join();
		t2.join();
		t3.join();
	}
}
